// src/pages/home.tsx
import React, { useState, useEffect, useRef } from "react";
import { useDispatch, useSelector } from 'react-redux';
import { toggleTheme, selectCurrentTheme } from '../../features/theme/themeSlice';
import Dren from "../3Dren/index";
import Zhongyinwen from "../zhongyinwen";
import { useTranslation } from "react-i18next";
import Voice from '../Voice/SpeechToText';
import "./index.css";

// 表情选择器组件
const EmojiPicker = ({ onSelect }: { onSelect: (emoji: string) => void }) => {
  // 常用表情列表
  const emojis = ['😀', '😂', '❤️', '🔥', '👍', '👎', '🎉', '🤔', '😍', '🙏'];

  return (
    <div className="emoji-picker">
      {emojis.map((emoji, index) => (
        <span
          key={index}
          className="emoji-option"
          onClick={() => onSelect(emoji)}
        >
          {emoji}
        </span>
      ))}
    </div>
  );
};

// 定义弹幕数据类型
interface Danmu {
  text: string;
  key: number;
  startTime: number;
  duration: number;
  top: string;
  left: string;
  speed: number;
  color: string;
  direction: 'left' | 'right';
  isEmoji?: boolean; // 标记是否为纯表情
}

function Home() {
  const { t } = useTranslation();
  const dispatch = useDispatch();
  const currentTheme = useSelector(selectCurrentTheme);
  const videoRef = useRef<HTMLVideoElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  // 弹幕相关状态
  const [comments, setComments] = useState<Danmu[]>([]);
  const [inputValue, setInputValue] = useState("");
  const [currentTime, setCurrentTime] = useState(0);
  const [showEmojiPicker, setShowEmojiPicker] = useState(false); // 控制表情选择器显示

  // 示例弹幕数据
  const presetDanmus: Danmu[] = [
    { text: "第一！", key: 1, startTime: 5, duration: 8, top: "10%", left: "10%", speed: 1, color: "#ff0000", direction: 'right' },
    { text: "这个视频不错", key: 2, startTime: 10, duration: 8, top: "30%", left: "80%", speed: 1.2, color: "#00ff00", direction: 'left' },
    { text: "哈哈哈😂", key: 3, startTime: 15, duration: 8, top: "50%", left: "20%", speed: 0.8, color: "#0000ff", direction: 'right' },
    { text: "❤️", key: 4, startTime: 20, duration: 8, top: "70%", left: "90%", speed: 1.5, color: "#ffff00", direction: 'left', isEmoji: true },
    { text: "666🎉", key: 5, startTime: 25, duration: 8, top: "90%", left: "30%", speed: 1, color: "#ff00ff", direction: 'right' },
  ];

  // 初始化时加载预设弹幕
  useEffect(() => {
    setComments(presetDanmus);
  }, []);

  // 监听视频时间更新
  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    const handleTimeUpdate = () => {
      setCurrentTime(video.currentTime);
    };

    video.addEventListener('timeupdate', handleTimeUpdate);
    return () => {
      video.removeEventListener('timeupdate', handleTimeUpdate);
    };
  }, []);

  // 发送弹幕
  const handleSubmit = () => {
    if (inputValue.trim() === "" || !videoRef.current) return;

    // 检查是否为纯表情
    const isEmojiOnly = /^[\uD800-\uDBFF][\uDC00-\uDFFF]|[\u2600-\u27FF]|[\uD83C][\uDF00-\uDFFF]|[\uD83D][\uDC00-\uDE4F]|[\uD83D][\uDE80-\uDEFF]$/.test(inputValue.trim());

    // 随机决定弹幕方向
    const direction = Math.random() > 0.5 ? 'right' : 'left';

    const newDanmu: Danmu = {
      text: inputValue,
      key: Date.now(),
      startTime: videoRef.current.currentTime,
      duration: isEmojiOnly ? 5 : 8 + Math.random() * 4, // 纯表情显示时间短一些
      top: `${Math.floor(Math.random() * 80) + 10}%`,
      left: direction === 'right'
        ? `${Math.floor(Math.random() * 30)}%`
        : `${Math.floor(Math.random() * 30) + 70}%`,
      speed: isEmojiOnly ? 0.5 : 0.8 + Math.random() * 0.8, // 纯表情移动慢一些
      color: isEmojiOnly
        ? '#ffffff' // 纯表情使用白色
        : `hsl(${Math.random() * 360}, 100%, 50%)`,
      direction,
      isEmoji: isEmojiOnly
    };

    setComments((prev) => [...prev, newDanmu]);
    setInputValue("");
    setShowEmojiPicker(false); // 发送后关闭表情选择器
  };

  // 选择表情
  const handleEmojiSelect = (emoji: string) => {
    setInputValue(prev => prev + emoji);
  };

  // 计算弹幕当前位置
  const calculateDanmuPosition = (danmu: Danmu) => {
    if (currentTime < danmu.startTime) {
      return {
        left: danmu.left,
        opacity: 0,
        transform: 'translateX(0)'
      };
    }

    if (currentTime > danmu.startTime + danmu.duration) {
      return {
        left: danmu.left,
        opacity: 0,
        transform: danmu.direction === 'right'
          ? 'translateX(100vw)'
          : 'translateX(-100vw)'
      };
    }

    const progress = (currentTime - danmu.startTime) / danmu.duration;
    const transform = danmu.direction === 'right'
      ? `translateX(${progress * 100}vw)`
      : `translateX(-${progress * 100}vw)`;
    return {
      left: danmu.left,
      opacity: 1,
      transform
    };
  };

  const handleThemeToggle = () => {
    dispatch(toggleTheme());
  };

  const yvyinye = () => {
    window.location.href = "/style";
  };

  return (
    <>
      <div className="box">
        <div className="top"></div>
        <div className="zhongjian">
          <Dren></Dren>
          <div className="imagesshang">
            <div className="buanjian">
              <div className="aiz">
                <button onClick={handleThemeToggle}>
                  {t("switchTheme")}
                </button>
                <Zhongyinwen></Zhongyinwen>
              </div>
              <br />
              <div className="tou">
                <span className="soanaln">我好烦啊</span>
                <div className="niaoling"></div>
              </div>
            </div>

            <div className="images">
              <video
                ref={videoRef}
                src="public/videos/bw.mp4"
                className="video"
                controls
              ></video>

              <div className="input-container">
                <input
                  type="text"
                  className="inputs"
                  value={inputValue}
                  onChange={(e) => setInputValue(e.target.value)}
                  placeholder="输入弹幕内容或表情"
                />
                <button
                  className="emoji-btn"
                  onClick={() => setShowEmojiPicker(!showEmojiPicker)}
                >
                  😀
                </button>
                <button onClick={handleSubmit}>发送弹幕</button>

                {showEmojiPicker && (
                  <EmojiPicker onSelect={handleEmojiSelect} />
                )}
              </div>

              <div className="zhezhao" ref={containerRef}>
                {comments.map((comment) => {
                  const position = calculateDanmuPosition(comment);
                  return (
                    <span
                      className={`danmu ${comment.isEmoji ? 'emoji-danmu' : ''}`}
                      key={comment.key}
                      style={{
                        position: 'absolute',
                        top: comment.top,
                        left: position.left,
                        opacity: position.opacity,
                        color: comment.color,
                        transform: position.transform,
                        transition: `transform ${comment.duration / comment.speed}s linear`,
                        whiteSpace: 'nowrap',
                        willChange: 'transform',
                        fontSize: comment.isEmoji ? '24px' : '16px' // 表情大一些
                      }}
                    >
                      {comment.text}
                    </span>
                  );
                })}
              </div>
            </div>

            <Voice />
          </div>
        </div>
        <div className="dibu">
          <div className="yvyin" onClick={yvyinye}></div>
        </div>
      </div>
    </>
  );
}

export default Home;